﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CapstoneWinPhone.Data;
using CapstoneWinPhone.ViewModels;
using Expense = CapstoneWinPhone.Data.Expense;
using Location = Microsoft.Phone.Controls.Maps.Platform.Location;
using System.Device.Location;


namespace CapstoneWinPhone.ViewModels
{
    public partial class MainPivotPage : PhoneApplicationPage
    {
        public MainPivotPage()
        {
            InitializeComponent();
            FillInInformationFromUser();
            Loaded += FillInInformationFromUser;

            DataContext = App.ViewModel;
        }

        #region fillInInformationMethods
        public void FillInInformationFromUser()
        {
            FillMainPageInfo();
            FillHoursPageInfo();
            FillExpensesPageInfo();

            if (DataHolder._currentWeeklyTimestamp.GetCurrentTimeStamp() != null)
            {
                ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                ClockIn.Content = "Clock Out";
            }
        }

        public void FillInInformationFromUser(Object sender, RoutedEventArgs e)
        {
            FillMainPageInfo();
            FillHoursPageInfo();
            FillExpensesPageInfo();
            FillPayCalcInfo();
            FillMileagePageInfo();
            updateGPSSlider.Value = DataHolder._currentUser.GPS_UpdateSpeed;
            if (DataHolder._currentWeeklyTimestamp.ClockedIn())
            {
                ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                ClockIn.Content = "Clock Out";
            }
        }

        private void FillMainPageInfo()
        {
            hellotxtBlock.Text = "Hello " + DataHolder._currentUser._username;
            datetxtBlock.Text = "Today is: " + " " + DateTime.Now.ToString("MMMM dd yyyy");
            CurrentLogTotalTxtBlock.Text = "Current Expense Log's total: " + ((DataHolder._currentExpenseLog._totalAmount != 0) ? "$" + DataHolder._currentExpenseLog._totalAmount.ToString("#.##") : "$0.00");
            CurrentExpenseLogTotalTxtBlock.Text = CurrentLogTotalTxtBlock.Text;
        }

        private void FillHoursPageInfo()
        {
            if (DataHolder._currentWeeklyTimestamp.listOfTimestamps.Count > 0)
            {
                ListOfHours.ItemsSource =
                    DataHolder._currentWeeklyTimestamp.listOfTimestamps.Where(
                        ts => ts.IsFinishedTimeStamp).Reverse().Take(5);
                TotalHoursLoggedForThisWeek.Text = DataHolder._currentWeeklyTimestamp.TotalHoursAndMinutes();
                if (DataHolder._currentWeeklyTimestamp.ClockedIn())
                {
                    ClockedInChangeButton();
                }
                else
                {
                    ClockedOutChangeButton();
                }
            }
        }

        private void FillExpensesPageInfo()
        {
            CurrentLogTotalTxtBlock.Text = "Current Log's total: " + ((DataHolder._currentExpenseLog._totalAmount != 0) ? DataHolder._currentExpenseLog._totalAmount.ToString("#.##") : "0.00");
            ListOfExpenses.Items.Clear();
            foreach (Expense expense in DataHolder._currentExpenseLog._ListOfExpenses)
            {
                ListOfExpenses.Items.Add(expense);
            }
        }

        private void FillMileagePageInfo()
        {
            CurrentNameOfMileageReport.Text = DataHolder._currentMileageReport._name;
            txtTotalMile.Text = DataHolder._currentMileageReport._TotalMiles.ToString("#.##") + " miles";
            ChangeTrackingButtonOff();
        }

        private void FillPayCalcInfo()
        {
            List<string> taxrateamounts = new List<string>();
            for (int i = 4; i < 30; i++)
            {
                taxrateamounts.Add(i + "%");
            }
            taxRateListBox.ItemsSource = taxrateamounts;
            taxRateListBox.SelectedItem = 4;
        }

        #endregion

        #region ChangeAndUpdateMethods
        private void ClockInHours()
        {
            ClockedInChangeButton();
            //start timer and save start time
            DataHolder._currentWeeklyTimestamp.CreateFinishTimestamp();
        }

        private void ClockOutHours()
        {
            ClockedOutChangeButton();
            DataHolder._currentWeeklyTimestamp.CreateFinishTimestamp();
            TotalHoursLoggedForThisWeek.Text = DataHolder._currentWeeklyTimestamp.TotalHoursAndMinutes();
            FillHoursPageInfo();
        }

        private void GeoCoordinateWatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            var latitude = e.Position.Location.Latitude;
            var longitude = e.Position.Location.Longitude;

            var location = new Location { Latitude = latitude, Longitude = longitude };
            //Save the location
            App.GpsModel.locations.Add(location);
        }

        private void updateGPSSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            //change the GPS update settings.
            Slider s = sender as Slider;
            DataHolder._currentUser.GPS_UpdateSpeed = s.Value;
        }
        #endregion

        #region ClickMethods

        private void ClockIn_Click(object sender, RoutedEventArgs e)
        {
            Button clockIn = sender as Button;
            if (clockIn != null)
            {
                if (clockIn.Content.Equals("Clock In"))
                {
                    ClockInHours();

                }
                else
                {
                    ClockOutHours();
                }
            }

        }

        private void NewExpense_Click(object sender, RoutedEventArgs e)
        {
            if (DataHolder._currentExpenseLog != null)
            {
                NavigationService.Navigate(new Uri("/CreateExpensePage.xaml", UriKind.Relative));
            }
            else
            {
                NavigationService.Navigate(new Uri("/CreateExpenseLogPage.xaml", UriKind.Relative));
                NavigationService.Navigate(new Uri("/CreateExpensePage.xaml", UriKind.Relative));
            }
            CurrentLogTotalTxtBlock.Text = "Current Log's total: " + DataHolder._currentExpenseLog._totalAmount.ToString("#.##");
            CurrentExpenseLogTotalTxtBlock.Text = CurrentLogTotalTxtBlock.Text;
        }

        private void allTimeStampButtons_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/TimeStampViewer.xaml", UriKind.Relative));
        }

        private void TrackingButton_Click(object sender, RoutedEventArgs e)
        {
            //start and stop tracking
            if (App.GpsModel.locations == null)
            {
                App.GpsModel.locations = new Microsoft.Phone.Controls.Maps.LocationCollection();
                App.GpsModel.GeoCoordinateWatcher.Start();
                ChangeTrackingButtonOn();
            }
            else
            {
                ChangeTrackingButtonOff();
                App.GpsModel.Stop();
            }

        }

        private void emailMileageReport_Click(object sender, RoutedEventArgs e)
        {
            App.GpsModel.Stop();
            DataMethods.ComposeEmailMileageReport(DataHolder._currentMileageReport);
            NavigationService.Navigate(new Uri("/CreateMileageReportPage.xaml", UriKind.Relative));
        }

        private void emailExpenseLogButton_Click(object sender, RoutedEventArgs e)
        {
            DataMethods.ComposeEmailExpenseReport(DataHolder._currentExpenseLog);
            NavigationService.Navigate(new Uri("/CreateExpenseLogPage.xaml", UriKind.Relative));
        }

        #endregion

        #region changeButtonMethods

        private void ClockedInChangeButton()
        {
            ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
            ClockIn.Content = "Clock Out";
        }

        private void ClockedOutChangeButton()
        {
            ClockIn.Content = "Clock In";
            ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 0, 200, 0));
        }

        private void ChangeTrackingButtonOn()
        {
            TrackingButton.Content = "Stop Tracking";
            TrackingButton.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
        }

        private void ChangeTrackingButtonOff()
        {
            TrackingButton.Content = "Start Tracking";
            TrackingButton.Background = new SolidColorBrush(Color.FromArgb(255, 0, 200, 0));
        }

        #endregion

        private void ListOfHours_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ViewallMileageReportButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/MileageReportsViewer.xaml", UriKind.Relative));
        }

        private void ViewAllExpenseLogsButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ExpenseLogsViewer.xaml", UriKind.Relative));
        }

        private void CalculatePayrollButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                double payRate = Convert.ToDouble(payRateTextBox.Text);
                double hoursWorked = Convert.ToDouble(hoursTextBox.Text);
                double taxrate = Convert.ToDouble(taxRateListBox.SelectedItem.ToString().Replace("%", ""));

                AmountBeforeTaxesTextBlock.Text = (payRate * hoursWorked).ToString("#.##") + "";
                AmountAfterTaxesTextBlock.Text = ((payRate * hoursWorked) / (1 + (taxrate / 100))).ToString("#.##") + "";
            }
            catch (FormatException)
            {
                AmountBeforeTaxesTextBlock.Text = "The numbers you entered didn't work";
                AmountAfterTaxesTextBlock.Text = "";
            }

        }
    }
}